import { Input, InputProps } from 'antd';
import classNames from 'classnames';
import type { FC } from 'react';
import { useEffect, useRef } from 'react';

export interface BaseInputProps extends InputProps {
  showCount?: boolean;
}
const BaseInput: FC<BaseInputProps> = (props) => {
  const {
    showCount,
    placeholder = '请输入',
    value,
    maxLength = undefined,
    onChange,
    ...rest
  } = props;
  const input = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (showCount) {
      input.current?.setAttribute(
        'data-count',
        `${value ? value.toString().length : 0} / ${maxLength}`
      );
    }
  }, [value, showCount, maxLength]);
  return (
    <div className={classNames({ 'ant-input-textarea-show-count': showCount })} ref={input}>
      <Input
        placeholder={placeholder}
        maxLength={maxLength}
        value={value}
        onChange={(e) => {
          const { value } = e.target;
          const realValue = value ? String(value).trim() : value;
          e.target.value = realValue;
          onChange && onChange(e);
        }}
        {...rest}
      />
    </div>
  );
};

export default BaseInput;
